<template>
  <div
    ref="chart"
    style="width: 100%;height: 100%"
  ></div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'EchartPie1',
  /**
   * data 传入数据
   * xData x坐标值
   * areaColor 渐变色
   * unit 纵轴单
   */
  props: {
    yData: {
      type: Array,
      default: () => [100, 25, 15, 78]
    },
    areaColor: {
      type: Array,
      default: () => ['#F1B267', '#479FFE', '#69EAFE', '#90FFAD']
    },
    // 可修改配置项
    legend: {
      type: Array,
      default: () => ['煤矿企业', '化工企业', '政府企业单位', '食品企业']
    },
    unit: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      chart: null,
      option: null,
      index: 0,
      obj: {
        num: '',
        title: ''
      }
    }
  },
  watch: {
    index: {
      handler (i) {
        if (i < this.yData.length) {
          this.$nextTick(() => {
            this.setChartOption(this.chart, this.yData)
          })
        } else {
          this.index = 0
        }
      },
      immediate: true
    }
  },
  computed: {
    getPercent () {
      let total = 0
      this.yData.forEach((item) => {
        total += item
      })
      return total
    }
  },
  mounted () {
    this.chart = echarts.init(this.$refs.chart)
  },
  beforeDestroy () {
    // this.chart.dispose()
  },
  methods: {
    // 设置option
    setChartOption (chart, yData) {
      const color = this.areaColor
      const value = (this.obj.num / this.getPercent) * 100
      const int = value.toFixed(2).split('.')[0]
      this.option = {
        title: [
          {
            text:
              this.obj.num === ''
                ? '{a|}{d| }'
                : '{a|' + int + '}{d|' + '%' + '}',
            x: 'center',
            top: '35%',
            textStyle: {
              rich: {
                a: {
                  fontSize: 18,
                  fontFamily: 'FZZhengHeiS-EB-GB',
                  color: '#333'
                },
                d: {
                  fontSize: 12,
                  fontFamily: 'FZZhengHeiS-EB-GB',
                  color: '#333',
                  padding: [0, 0, 5, 0]
                }
              }
            }
          },
          {
            text: `${this.formatterTitle(this.obj.title)}`,
            x: 'center',
            top: '50%',
            textStyle: {
              color: '#666',
              fontFamily: 'Microsoft YaHei',
              fontWeight: 400,
              fontSize: 12
            }
          }
        ],
        grid: {
          left: 0,
          top: 0,
          right: 0,
          bottom: 0,
          containLabel: true
        },
        tooltip: {
          show: false
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: ['50%', '76%'],
            center: ['50%', '50%'],
            data: this.yData,
            z: 9,
            emphasis: {
              // 使用emphasis
              disable: false,
              scale: true, // 不缩放
              scaleSize: 4 // 为了防止失效直接设置未0
            },
            animationEasing: 'elasticOut',
            itemStyle: {
              normal: {
                borderWidth: 2,
                borderColor: 'RGBA(229, 243, 254, 1)',
                color: function (colors) {
                  return color[colors.dataIndex]
                }
              }
            },
            labelLine: { show: false },
            label: { show: false }
          },
          {
            type: 'pie',
            radius: ['50%', '63%'],
            center: ['50%', '50%'],
            silent: true,
            hoverAnimation: false,
            z: 10,
            itemStyle: {
              normal: {
                borderWidth: 2,
                borderColor: 'RGBA(229, 243, 254, 1)',
                color: 'rgba(255, 255, 255,.6)'
              }
            },
            labelLine: { show: false },
            label: { show: false },
            data: this.yData
          },
          {
            name: '虚线外圆',
            type: 'pie',
            silent: true,
            radius: ['83%', '86%'],
            center: ['50%', '50%'],
            label: {
              show: false
            },
            data: this.generateData(50, 25, 20, '#E6E6E6')
          }
        ]
      }

      chart.setOption(this.option)
      this.changeAuto(chart)
      const that = this
      window.addEventListener('resize', function () {
        that.chart.resize()
      })
    },
    // 切换
    changeAuto (chart) {
      const that = this
      setTimeout(function () {
        if (that.index < that.yData.length) {
          chart.dispatchAction({ type: 'downplay', seriesIndex: 0 })
          chart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: that.index
          })
          that.$set(that.obj, 'title', that.legend[that.index])
          that.$set(that.obj, 'num', that.yData[that.index])

          that.index++
        } else {
          that.index = 0
        }
      }, 2000)
    },
    // 外圆环图
    generateData (totalNum, bigvalue, smallvalue, color) {
      const dataArr = []
      for (let i = 0; i < totalNum; i++) {
        if (i % 2 === 0) {
          dataArr.push({
            name: (i + 1).toString(),
            value: bigvalue,
            itemStyle: {
              normal: {
                color: color,
                borderWidth: 0
              }
            }
          })
        } else {
          dataArr.push({
            name: (i + 1).toString(),
            value: smallvalue,
            itemStyle: {
              normal: {
                color: 'rgba(0,0,0,0)',
                borderWidth: 0
              }
            }
          })
        }
      }
      return dataArr
    },
    formatterTitle (params) {
      let newParamsName = ''
      const paramsNameNumber = params.length
      const provideNumber = 4
      const rowNumber = Math.ceil(paramsNameNumber / provideNumber)
      if (paramsNameNumber > provideNumber) {
        for (let p = 0; p < rowNumber; p++) {
          let tempStr = ''
          const start = p * provideNumber
          const end = start + provideNumber
          if (p === rowNumber - 1) {
            tempStr = params.substring(start, paramsNameNumber)
          } else {
            tempStr = params.substring(start, end) + '\n'
          }
          newParamsName += tempStr
        }
      } else {
        newParamsName = params
      }
      return newParamsName
    }
  }
}
</script>

<style lang="scss" scoped>
// .echarts3-wrap {
// }
</style>
